package com.hoku.auth.dao;

import com.google.common.collect.Maps;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.provider.client.BaseClientDetails;
import org.springframework.stereotype.Repository;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Map;
import java.util.concurrent.TimeUnit;


/**
 * @author ZHUFEIFEI
 */
@Repository
public class ClientDaoImpl implements IClientDao, InitializingBean {

    @Autowired
    private PasswordEncoder encoder;

    private Map<String, BaseClientDetails> memory = Maps.newConcurrentMap();

    @Override
    public BaseClientDetails getByClientId(String clientId) {
        return this.memory.get(clientId);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        for (int i = 1; i < 10 ; i++) {
            BaseClientDetails client = new BaseClientDetails();
            client.setClientId("client"+i);
            //noop 无操作，明文密码
            client.setClientSecret(this.encoder.encode("123456"));
            client.setAuthorizedGrantTypes(Arrays.asList("authorization_code",
                    "client_credentials", "refresh_token", "password", "implicit"));
            //client.setResourceIds();
            client.setScope(Arrays.asList("server", "hello"));
            client.setAuthorities(AuthorityUtils.createAuthorityList("client_role"));
            //access token 有效期1天
            client.setAccessTokenValiditySeconds((int) TimeUnit.DAYS.toSeconds(1));
            //refresh token 有效期1天
            client.setRefreshTokenValiditySeconds((int) TimeUnit.DAYS.toSeconds(1));
            client.addAdditionalInformation("key"+i, "value");
            client.setRegisteredRedirectUri(new HashSet<>(Arrays.asList("http://localhost:8080/login")));
            this.memory.put(client.getClientId(), client);
        }
    }
}
